package me.uniauto.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hardy on 2018/2/24.
 * 解析request
 */
public class RequestUtil {

    /**
     * 获取header里面的参数
     * @param request
     * @return
     */
    public static Map headerMap(HttpServletRequest request){
        Map map = new HashMap<>();
        Enumeration enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()){
            String pname = (String) enumeration.nextElement();
            String pvalue = request.getHeader(pname);
            if(pvalue!=null&&pvalue.length()>0){
                map.put(pname,pvalue);
            }
        }
        return map;
    }


    /**
     * 获取params
     * @param request
     * @return
     */
    public static Map paramsMap(HttpServletRequest request){
        Map map = new HashMap<>();

        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()){
            String paramsKey = (String) enumeration.nextElement();
            String[] paramsValueStr = request.getParameterValues(paramsKey);
            if(paramsValueStr.length==1){
                String paramsValue = paramsValueStr[0];
                if(paramsValue.length()>0){
                    map.put(paramsKey,paramsValue);
                }
            }

        }
        if (map.containsKey("startIndex") && map.containsKey("pageSize")) {
            int startIndex = Integer.parseInt(map.get("startIndex") + "");
            int pageSize = Integer.parseInt(map.get("pageSize") + "");
            map.put("startIndex", startIndex * pageSize);
            map.put("pageSize", pageSize);
        } else {
            map.put("startIndex", 0);
            map.put("pageSize", 10);
        }
        return map;
    }

}
